/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-23
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-13
 * @Description: 用户服务
 */
import 'package:chat_client/repositories/auth_repository.dart';
import 'package:chat_client/services/api_service.dart';
import 'package:chat_client/utils/image-picker/image_picker_helper.dart';
import 'package:dio/dio.dart';
import 'package:image_picker/image_picker.dart';
import 'package:chat_client/models/user_model.dart';

class UserService {
  // 单例模式
  UserService._internal();
  static final UserService _instance = UserService._internal();
  static UserService get instance => _instance;

  final ApiService apiService = ApiService.instance;
  final AuthRepository authRepository = AuthRepository.instance;

  // 获取远程用户个人信息
  Future getRemoteUserInfo() async {
    final response = await apiService.get('/user/info');
    final User user = User.fromJson(response['data']);
    authRepository.setUser(user);
  }

  // 获取本地用户信息
  getLocalUserInfo() {
    return authRepository.userSelf;
  }

  // 更新用户个人信息
  Future<void> updateUserInfo(Map<String, dynamic> userInfo) async {
    final response = await apiService.put('/user/update/', userInfo);
    authRepository.updateUser(response['data']);
  }

  // 更新用户头像
  Future<void> updateAvatar(XFile imageFile) async {
    MultipartFile? avatarFile;
    avatarFile = await ImagePickerHelper.convertXFileToMultipart(imageFile);
    final formData = FormData.fromMap({'avatar': avatarFile});
    final response = await apiService.postFormData('/user/avatar', formData);
    authRepository.updateUser(response['data']);
  }

  // 修改用户密码
  Future<bool> changePassword({
    required String oldPassword,
    required String newPassword,
    required String captchaCode,
    required String captchaUid,
  }) async {
    final response = await apiService.put('/auth/updatePassword',
        {'oldPassword': oldPassword, 'newPassword': newPassword});
    if (response['statusCode'] == 200) return true;
    return false;
  }

  // 注销账号
  Future<dynamic> logout({
    required String password,
    required String captchaUid,
    required String captchaCode,
  }) async {
    final response = await apiService.delete('/auth/delete', data: {
      'password': password,
      'captchaUid': captchaUid,
      'captchaCode': captchaCode
    });
    if (response['statusCode'] == 200) return true;
    return response['message'];
  }
}
